<script setup>
import useMainContent from '@/hooks/main'
import {commodityContentConfig} from '@/views/main/commodity/config/content.config'
import {commodityDetailChangeConfig, commodityDialogChangeConfig} from '@/views/main/commodity/config/change.config'
import {ref} from 'vue'
import useMainStore from '@/store/main'
import {notificationMess} from '@/utils/message'
import {storeToRefs} from 'pinia'
import useCommodityStore from '@/store/commodity'
import {defaultCommodityDetailFormData} from '@/views/main/commodity/config/default'
import {ElMessageBox} from 'element-plus'

//获取页面钩子
const [popupRef, handleEdit] = useMainContent()
const [detailPopupRef, handleEditDetail] = useMainContent()

//获取主store
const mainStore = useMainStore()

//分类数据
const catagoryArr = ref([])
mainStore.fetchListAction('category').then((res) => catagoryArr.value = res)

//获取农品store
const commodityStore = useCommodityStore()

//新建农品的id
const commodity_id = ref('')

//新建农品
const handleAdd = async (table, data) => {
  commodity_id.value = await commodityStore.fetchAddAction(table, data)
  //打开详情界面
  handleEditDetail({...defaultCommodityDetailFormData, commodity_id: commodity_id.value})
}

//在新建农品界面的详情页准备关闭前的回调
const handleBeforeClose = async (done) => {
  //删除已经上传的农品
  ElMessageBox.confirm('未保存详情的农品会被自动删除', '确定关闭表单？', {type: 'warning'})
    .then(async () => {
      await mainStore.fetchDeleteAction('commodity', commodity_id.value)
      done()
    })
    .catch(() => {
    })
}

//删除农品
const handleDelete = async (_, _id) => {
  //删除农品表
  await mainStore.fetchDeleteAction('commodity', _id)
  //删除农品详情表
  await mainStore.fetchDeleteByFieldAction('commodity_detail', 'commodity_id', _id, false)
}

//编辑详情
const handleClickDetail = async ({_id}) => {
  const res = (await mainStore.fetchGetDetailAction('commodity_detail', 'commodity_id', _id))[0]

  //打开详情界面
  handleEditDetail(res)
}
</script>

<template>
  <!-- 表格 -->
  <page-content :content-config="commodityContentConfig" @edit="handleEdit" :delete-fn="handleDelete">
    <!-- 编辑详情 -->
    <template #editDetail="row">
      <el-button text bg type="primary" @click="handleClickDetail(row)">详情</el-button>
    </template>
  </page-content>

  <!-- 弹出层 -->
  <page-change :change-config="commodityDialogChangeConfig" ref="popupRef" :new-fn="handleAdd">
    <!-- 分类 -->
    <template #catagory="{prop,value}">
      <el-select :model-value="value" @update:modelValue="popupRef.setForm(prop, $event)"
                 placeholder="请选择农品分类">
        <el-option v-for="{_id, name} in catagoryArr" :key="_id" :label="name" :value="_id"/>
      </el-select>
    </template>
  </page-change>

  <!-- 详情抽屉 -->
  <page-change :change-config="commodityDetailChangeConfig" ref="detailPopupRef" show-type="drawer"
               :before-new-callback="handleBeforeClose"/>
</template>

<style lang="scss" scoped>
</style>
